package com.rf.richfitwheel.admin.sys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.sys.dao.SysCertInfoMapper;
import com.rf.richfitwheel.admin.sys.dao.SysCertOrgPaymentMapper;
import com.rf.richfitwheel.admin.sys.model.SysCertInfo;
import com.rf.richfitwheel.admin.sys.model.SysCertInfoExample;
import com.rf.richfitwheel.admin.sys.model.SysCertOrgPayment;
import com.rf.richfitwheel.admin.sys.model.SysCertOrgPaymentExample;
import com.rf.richfitwheel.admin.sys.service.SysCertInfoService;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

/**
 * @author hushouquan
 */
@Service("sysCertInfoService")
public class SysCertInfoServiceImpl implements SysCertInfoService{
    
    @Autowired
    private SysCertInfoMapper sysCertInfoMapper;
    @Autowired
    private SysCertOrgPaymentMapper sysCertOrgPaymentMapper;
    /**
     * 保存或修改证书信息
     *
     * @param sysCertInfo 证书信息
     * @throws Exception 异常
     */
    @Override
    public void saveOrUpdate(SysCertInfo sysCertInfo) throws Exception{
        SysCertInfo old = sysCertInfoMapper.selectByPrimaryKey(sysCertInfo.getCertSn());
        if(old == null){
            //新增
            sysCertInfoMapper.insert(sysCertInfo);
        }else{
            sysCertInfoMapper.updateByPrimaryKey(sysCertInfo);
        }
    }
    
    /**
     * 验证ukey合法性（有效期、状态、用户匹配等）
     *
     * @param certInfo ukey信息
     * @return 验证结果
     */
    @Override
    public boolean checkUkeyAccess(Map<String, Object> certInfo) throws Exception{
        Assert.notNull(certInfo, "无法读取ukey信息");
        Assert.notNull(certInfo.get("certSN"), "无法读取ukey信息");
        String certSN = certInfo.get("certSN").toString().replaceAll(" ", "");
        String login = certInfo.get("login") == null ? null : certInfo.get("login").toString();
        String orgId = certInfo.get("orgId") == null ? null : certInfo.get("orgId").toString();
        if(UserUtil.getUser().getAccountName() == null){
            throw new BusinessException("Ukey信息与当前登录用户信息不匹配");
        }
        SysCertInfoExample example = new SysCertInfoExample();
        SysCertInfoExample.Criteria criteria = example.createCriteria();
        criteria.andCertSnIn(Arrays.asList(certSN.split(",")));
        criteria.andUserIdEqualTo(UserUtil.getUser().getAccountName());
        List<SysCertInfo> list = sysCertInfoMapper.selectByExample(example);
        if(list.isEmpty()){
            throw new BusinessException("Ukey信息与当前登录用户信息不匹配");
        }
        SysCertInfo sysCertInfo = list.get(0);
        //验证数据有效性
        Calendar nowDate = Calendar.getInstance();
        Calendar start = Calendar.getInstance();
        start.setTime(sysCertInfo.getStartTime());
        Calendar end = Calendar.getInstance();
        end.setTime(sysCertInfo.getEndTime());
        //验证是否过期
        if(nowDate.before(start)){
            throw new BusinessException("ukey已过期");
        }
        if(nowDate.after(end)){
            throw new BusinessException("ukey已过期");
        }
        //验证ukey状态
        if("1".equals(sysCertInfo.getCertStatus())){
            throw new BusinessException("证书未下载");
        }
        if("2".equals(sysCertInfo.getCertStatus())){
            throw new BusinessException("证书未激活");
        }
        if("4".equals(sysCertInfo.getCertStatus())){
            throw new BusinessException("证书已冻结");
        }
        if("5".equals(sysCertInfo.getCertStatus())){
            throw new BusinessException("证书已作废");
        }
        if("6".equals(sysCertInfo.getCertStatus())){
            throw new BusinessException("证书已过期");
        }
        if(!"1".equals(login)){
            SysCertOrgPaymentExample example1 = new SysCertOrgPaymentExample();
            SysCertOrgPaymentExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andCertSnEqualTo(certSN);
            criteria1.andOrgIdEqualTo(orgId);
            List<SysCertOrgPayment> list1 = sysCertOrgPaymentMapper.selectByExample(example1);
            if(list1.isEmpty()){
                throw new BusinessException("未对证书设置该企业的支付权限，请先联系管理员开通支付权限");
            }
            //非登录的时候才验证是否需要支付权限
            if(!Constant.COMMON_YES_OR_NO_YES.equals(list1.get(0).getPayment())){
                throw new BusinessException("未对证书设置该企业的支付权限，请先联系管理员开通支付权限");
            }
        }
        return true;
    }
    
    /**
     * 分页查询ukey信息
     *
     * @param params {username:,staffName:,certSn:,certStatus:,receStatus:}
     * @return 分页数据
     */
    @Override
    public PageUtils querySysCertInfoPage(Map<String, Object> params){
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Map<String, Object>> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        JSONObject dataForm = JSONObject.fromObject(params.get("dataForm"));
        Map<String, Object> paramsNew = new HashMap<>();
        if (StringUtils.isNotBlank(dataForm.get("username"))) {
            paramsNew.put("username", "%" + dataForm.get("username").toString() + "%");
        }
        if (StringUtils.isNotBlank(dataForm.get("staffName"))) {
            paramsNew.put("staffName", "%" + dataForm.get("staffName").toString() + "%");
        }
        if (StringUtils.isNotBlank(dataForm.get("staffId"))) {
            paramsNew.put("staffId", "%" + dataForm.get("staffId").toString() + "%");
        }
        if (StringUtils.isNotBlank(dataForm.get("certSn"))) {
            paramsNew.put("certSn", "%" + dataForm.get("certSn").toString() + "%");
        }
        if (StringUtils.isNotBlank(dataForm.get("certStatus"))) {
            paramsNew.put("certStatus", dataForm.get("certStatus").toString());
        }
        if (StringUtils.isNotBlank(dataForm.get("receStatus"))) {
            paramsNew.put("receStatus", dataForm.get("receStatus").toString());
        }
        if (StringUtils.isNotBlank(dataForm.get("payment"))) {
            paramsNew.put("payment", dataForm.get("payment").toString() );
        }
        if (StringUtils.isNotBlank(dataForm.get("paymentStatus"))) {
            paramsNew.put("paymentStatus", dataForm.get("paymentStatus").toString());
        }
        if (StringUtils.isNotBlank(dataForm.get("orgName"))) {
            paramsNew.put("orgName", "%" + dataForm.get("orgName").toString() + "%");
        }
        if (StringUtils.isNotBlank(dataForm.get("step"))) {
            if("1".equals(dataForm.get("step").toString())){
                paramsNew.put("orderParam", "order by payment_status, cert_sn");
            } else{
                paramsNew.put("orderParam", "order by cert_sn");
            }
        }
        List<Map<String, Object>> list = sysCertInfoMapper.selectSysCertInfoPage(paramsNew);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }
    
    /**
     * 开通支付权限
     *
     * @param certInfo 证书和机构关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setPaymentApply(Map<String, Object>[] certInfo){
        for(Map<String, Object> map : certInfo){
            if(StringUtils.isNotBlank(map.get("id"))){
                SysCertOrgPayment sysCertOrgPayment = sysCertOrgPaymentMapper.selectByPrimaryKey(map.get("id").toString());
                sysCertOrgPayment.setPaymentStatus("2");
                sysCertOrgPaymentMapper.updateByPrimaryKey(sysCertOrgPayment);
            }else{
                SysCertOrgPaymentExample example = new SysCertOrgPaymentExample();
                SysCertOrgPaymentExample.Criteria criteria = example.createCriteria();
                criteria.andCertSnEqualTo(map.get("cert_sn").toString());
                criteria.andOrgIdEqualTo(map.get("org_id").toString());
                List<SysCertOrgPayment> l1 = sysCertOrgPaymentMapper.selectByExample(example);
                if(!l1.isEmpty()){
                    SysCertOrgPayment sysCertOrgPayment = l1.get(0);
                    sysCertOrgPayment.setPaymentStatus("2");
                    sysCertOrgPaymentMapper.updateByPrimaryKey(sysCertOrgPayment);
                }else{
                    SysCertOrgPayment sysCertOrgPayment = new SysCertOrgPayment();
                    sysCertOrgPayment.setId(UuidUtil.get32UUID());
                    sysCertOrgPayment.setCertSn(map.get("cert_sn").toString());
                    sysCertOrgPayment.setOrgId(map.get("org_id").toString());
                    sysCertOrgPayment.setPayment(Constant.COMMON_YES_OR_NO_NO);
                    sysCertOrgPayment.setPaymentStatus("2");
                    sysCertOrgPaymentMapper.insert(sysCertOrgPayment);
                }
            }
        }
    }
    
    /**
     * 关闭支付权限
     *
     * @param idList 记录id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setPaymentCancel(List<String> idList){
        for(String s : idList){
            SysCertOrgPayment sysCertOrgPayment = new SysCertOrgPayment();
            sysCertOrgPayment.setId(s);
            sysCertOrgPayment.setPayment(Constant.COMMON_YES_OR_NO_NO);
            sysCertOrgPayment.setPaymentStatus("1");
            sysCertOrgPaymentMapper.updateByPrimaryKeySelective(sysCertOrgPayment);
        }
    }
    
    /**
     * 审批支付权限
     *
     * @param idList 记录id
     */
    @Override
    public void paymentApplyDone(List<String> idList){
        Date dateNow = new Date();
        for(String s : idList){
            SysCertOrgPayment sysCertOrgPayment = new SysCertOrgPayment();
            sysCertOrgPayment.setId(s);
            sysCertOrgPayment.setPayment(Constant.COMMON_YES_OR_NO_YES);
            sysCertOrgPayment.setPaymentStatus("3");
            sysCertOrgPayment.setPaymentTime(dateNow);
            sysCertOrgPaymentMapper.updateByPrimaryKeySelective(sysCertOrgPayment);
        }
    }
}
